<?php


namespace App\Http\Controllers\user;


use App\Engine\BaseCommon;
use App\Engine\BaseController;
use App\Engine\TokenService;
use App\Exceptions\ApiException;
use App\Http\service\PayService;
use App\Models\Order as OrderModel;
use Illuminate\Support\Facades\DB;
use Workerman\Protocols\Http\Request;
use function app\Utils\go;

class Order extends BaseController
{
    /**微信调取支付
     * @return array
     * @throws ApiException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function create_order()
    {
        $order=new OrderModel();
        $this->validate($this->request,$order->rule,$order->ruleMessage);
        $user=$order->check_phone();
        DB::beginTransaction();
        try {
            $create=[
                "order_num"=>(new BaseCommon())->create_order_num("D"),
                "uid"=>TokenService::getCurrentUid(),
                "price"=>$this->post["price"],
                "pay_state"=>0,
                "state"=>0,
                "phone"=>$user["phone"]
            ];
            $res=$order->create($create);
            $create["openid"]=$user["openid"];
            $result=(new PayService())->wx_pay($create);
            DB::commit();
            return go($result);
        }catch (\Exception $exception){
            DB::rollBack();
            throw new ApiException($exception->getMessage());
        }

    }

    public function order_notify()
    {
        $app=(new PayService())->get_app();
        $response =  $app->handlePaidNotify(function($message, $fail){
            if($message['return_code']=='SUCCESS'){
                $order=OrderModel::where(['order_num'=>$message['out_trade_no']])->first();

                if (!$order){
                    return false;
                }
                if($order['pay_state']==1)
                    return true;
                $res=OrderModel::where("id",$order["id"])->update(["pay_state"=>1,"pay_time"=>time()]);
            }
            return true; // 返回处理完成
        });
    }
}
